import threading
from tkinter import Button
import requests
import json
from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.window.config_window.config_button import create_config_button
from util.comm.path import getConfigPath
from util.comm.msg_util import msg
from util.database.redis import clear_redis
import tkinter as tk

class ClsRedis():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.elements = []

        self.config_path = getConfigPath()
        self.button = create_config_button(self, True)

        # 打开文件并读取JSON数据
        with open(self.config_path, 'r', encoding="utf-8") as file:
            data = json.load(file)
        if isinstance(data, list):
            # for index, c in enumerate(data):
            #     self.button = Button(self.tab, text=c['name'], command=lambda config=c: self.cls_redis_sync(config))
            #     self.button.pack(side='left', fill=None, expand=False, anchor='ne', padx=20, pady=30)
            #     self.elements.append(self.button)
            row = 1
            column = 0
            self.frame_b = tk.Frame(self.tab)
            for index, c in enumerate(data):
                # 增加三级内容
                name = c['name']
                conf = c
                self.button = Button(self.frame_b, text=name, command=lambda config=conf: self.cls_redis_sync(config), width=12)
                self.button.grid(row=row, column=column, padx=5, pady=5)
                column += 1
                if column % 4 == 0:  # 每四个按钮换行
                    column = 0
                    row += 1
                    new_row = tk.Frame(self.frame_b)
                    new_row.grid(row=row, column=column, sticky='news')
                self.elements.append(self.frame_b)
            self.frame_b.pack(side="left", fill=None, expand=False, anchor='ne', pady=10)
        else:
            print(data)

    def cls_redis_sync(self, config):
        if hasattr(self, 'cls_redis_sync_flag') and self.cls_redis_sync_flag == '1':
            msg('正在清理缓存,请勿重复操作')
            return
        self.cls_redis_sync_flag = '1'
        wrap_print_entry = wrap_with_try_except(self.cls_redis)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=(config,)), lambda: self.reset_sync()).execute_async()

    def reset_sync(self):
        self.cls_redis_sync_flag = '0'

    def cls_redis(self, config):
        mode = config['mode']
        if mode == 1:
            urls = config['url']
            url_list = urls.split(',')
            for url in url_list:
                print('url---%s' % url)
                headers = {'Content-Type': 'application/json'}  # 根据需要设定请求头
                res = requests.post(url, headers=headers)
                print(res.text)
        elif mode == 2:
            # 执行命令行命令
            hosts = config['host']
            keys = config['key']
            host_list = hosts.split(',')
            key_list = keys.split(',')
            for host in host_list:
                hp = host.split(":")
                h = hp[0]
                p = hp[1]
                for key in key_list:
                    clear_redis(h, p, key)
        msg('缓存已清理')
